package com.fiap.activities;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class SocialEngineViewer extends Activity implements OnTouchListener, Handler.Callback{

	private static final int CLICK_ON_WEBVIEW = 1;
	private static final int CLICK_ON_URL = 2;

	private final Handler handler = new Handler(this);
	
	private WebViewClient client;
	private WebView webView;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.socialengine_webview);
		webView = (WebView) findViewById(R.id.web_view);
		webView.setOnTouchListener(this);
		
		webView.getSettings().setJavaScriptEnabled(true); // enable JS for better page rendering
//		webView.loadUrl("http://10.0.2.2/socialengine/login");
		webView.loadUrl("http://10.0.2.2/socialengine45/login");
//		webView.loadUrl("http://runnersteam.no-ip.biz/socialengine/login");
		
		this.webView.setWebViewClient(new WebViewClient(){

		    @Override
		    public boolean shouldOverrideUrlLoading(WebView view, String url){
		      if (url.contains("activities")){
		    	  Intent activitiesMenu = new Intent(getApplicationContext(), MainMenuActivity.class);
		    	  activitiesMenu.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		          startActivity(activitiesMenu);
		      } else {
		    	  view.loadUrl(url);  
		      } 
		      
		      return true;
		    }
		});
	}
	
	@Override
	public boolean onTouch(View v, MotionEvent event) {
	    if (v.getId() == R.id.web_view && event.getAction() == MotionEvent.ACTION_DOWN){
	        handler.sendEmptyMessageDelayed(CLICK_ON_WEBVIEW, 500);
	    }
	    return false;
	}
	
//	@Override
//	public boolean onCreateOptionsMenu(Menu menu) {
//		// Inflate the menu; this adds items to the action bar if it is present.
//		getMenuInflater().inflate(R.menu.main, menu);
//		return true;
//	}
	
	@Override
	public boolean handleMessage(Message msg) {
	    if (msg.what == CLICK_ON_URL){
	        handler.removeMessages(CLICK_ON_WEBVIEW);
	        return true;
	    }
	    if (msg.what == CLICK_ON_WEBVIEW){
	        Toast.makeText(this, "WebView clicked", Toast.LENGTH_SHORT).show();
	        return true;
	    }
	    return false;
	}

}
